package com.tron.dobest.schedule;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class TronTaskRegistrar implements DisposableBean {

    private  final Logger log = LoggerFactory.getLogger(this.getClass());
    /**
     * 定时任务存储器
     */
    private final Map<Runnable, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>();

    @Autowired
    private TaskScheduler taskScheduler;


    /**
     * 新增定时任务
     * @param task
     * @param cronExpression
     */
    public void addCronTask(Runnable task, String cronExpression) {
        addCronTask(new CronTask(task, cronExpression));
        log.info("当前执行的定时任务有:{}个",scheduledTasks.size());
    }

    public void addCronTask(CronTask cronTask) {
        if (cronTask != null) {
            Runnable task = cronTask.getRunnable();
            if (this.scheduledTasks.containsKey(task)) {
                removeCronTask(task);
            }
            this.scheduledTasks.put(task, scheduleCronTask(cronTask));
        }
    }

    /**
     * 移除定时任务
     * @param task
     */
    public void removeCronTask(Runnable task) {
        ScheduledTask scheduledTask = this.scheduledTasks.remove(task);
        if (scheduledTask != null) {
            scheduledTask.cancel();
        }
        log.info("当前执行的定时任务有:{}个",scheduledTasks.size());
    }

    /**
     * 根据id移除定时任务
     * @param id
     */
    public void removeCronTaskById(String id) {
        Runnable runnableById = getRunnableById(id);
        if (null != runnableById) {
            removeCronTask(runnableById);
        }
    }

    /**
     * 根据id返回定时任务
     * @param id
     * @return
     */
    private Runnable getRunnableById(String id) {
        Set<Runnable> keySet = scheduledTasks.keySet();
        Iterator<Runnable> iterator = keySet.iterator();
        while (iterator.hasNext()) {
            SchedulingRunnable schedulingRunnable = (SchedulingRunnable) iterator.next();
            if (id.equals(schedulingRunnable.getId())) {
                return schedulingRunnable;
            }
        }
        return null;
    }

    public ScheduledTask scheduleCronTask(CronTask cronTask) {
        ScheduledTask scheduledTask = new ScheduledTask();
        scheduledTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
        return scheduledTask;
    }


    @Override
    public void destroy() {
        for (ScheduledTask task : this.scheduledTasks.values()) {
            task.cancel();
        }
        this.scheduledTasks.clear();
    }
}
